/******************* 公共变量 *******************/
var local,
	marker,
	gpsDetail,
	searchResult = '',
	keyword = '',
	inviteObj = core.ls('inviteObj', 'o') || {},
	lng = 0,
	lat = 0,
	city = '',
	add = '',
	site = '',
	judge = true,
	vm;

function closeLayer() {
	layer.closeAll();
}

/******************* 初始化微信 *******************/
wx.ready(function () {
	wx.checkJsApi({  
		jsApiList : ['getLocation', 'uploadImage','previewImage','chooseImage','scanQRCode','startRecord','stopRecord','onVoiceRecordEnd','playVoice','onVoicePlayEnd','onMenuShareAppMessage'],  
		success : function(res) {  
		},
		complete: function (data) {
			if (data.checkResult.getLocation == 'no') {
				useGps(true);
			} else {
				useGps();
			}
		}
	});
});

function useGps(useBaidu) {
	/******************* Vue初始化代码 *******************/
	vm = new Vue({
		el: '.wrap',
		data: {
			position: ''
		},
		methods: {
			del: function () {
				this.position = '';
				searchResult = '';
			},
			showResult: function () {
				if ($('.layui-m-layer').length == 0) {
					layer.open({
						type: 1,
						content: '<article><section class="con"></section></article>',
						anim: 'up',
						className: 'map-search',
						shade: false,
						shadeClose: false,
						style: 'overflow: auto; position:fixed; bottom:0; left:0; width: 100%; height: 50%; border:none;',
						success: function () {
							$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input input').val(keyword);
							$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con').html(searchResult);
						}
					});
				}
			},
			closeResult: function () {
				layer.closeAll();
			},
			search: function (event) {
				var $this = $(event.target),
					keyword = $this.val();

				local.search(keyword, {
					forceLocal: true,
					customData: CustomData
				});
			}
		},
		computed: {
			
		},
		components: {
			
		},
		created: function () {
			
		},
		mounted: function () {
			/******************* 公共变量 *******************/
			var $positionName = $('body .wrap .position-add h2'),
				$positionAdd = $('body .wrap .position-add p'),
				$showSearch = $('html body .wrap .invite-map .input span');
				
			// common.bindBack();
			/******************* 页面初始化代码 *******************/
			$('#map').height(winHeight - $('html body .wrap .invite-map .position-add').height() - headerTitleHeight);

			/******************* 获取当前位置的IP地址 *******************/
			// core.bdMap({
			// 	selector: 'allmap',
			// 	device: 'mb',
			// 	ipDetail: function (data) {
			// 		data.content.address_component.city
			// 	},
			// 	gpsDetail: function (data) {
			// 		$('body .index .local .local-header a').html(data.result.addressComponent.city.substr(0, data.result.addressComponent.city.length - 1));
			// 	}
			// });

			// 地图中展示搜索的input事件
			// $('html body .wrap .invite-map .input input').on('input', function () {
			// 	local.search($(this).val(), {
			// 		forceLocal: true
			// 	});
			// });

			/******************* 全屏弹窗功能 *******************/
			// 点击弹出弹窗
			$showSearch.on('click', function () {
				//页面层
				layer.open({
					type: 1,
					content: '<article><section class="input"><input type="text" name="" value=""><span>取消</span></section><section class="con"></section></article>',
					anim: 'up',
					className: 'map-search',
					shadeClose: false,
					style: 'position:fixed; bottom:0; left:0; width: 100%; height: 100%; border:none;',
					success: function () {
						$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input input').val(keyword);
						$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con').html(searchResult);
						
					}
				});
				$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input input').focus();
			});

			// 关闭弹窗
			$('body').on('tap', '.layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input span', function () {
				layer.closeAll();
			});

			// 弹窗搜索的input事件
			$('html body').on('input', '.layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input input', function () {
				keyword = $(this).val();

				$showSearch.html(keyword);
				local.search(keyword, {
					forceLocal: true
				});
			});
			
			/******************* 半屏弹窗功能 *******************/

			// 搜索结果选择功能
			core.tabSwitch({
				tit: 'html body',
				selector: '.layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con div',
				event: 'tap',
				active: false
			}, function ($this, thisIndex, $thisCon, beforeIndex, isInit) {
				if (!isInit) {
					searchResult = $('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con').html();
					$positionName.html($this.children('span').html()).attr({
						lng: $this.attr('lng'),
						lat: $this.attr('lat')
					});
					// lng = $this.attr('lng');
					// lat = $this.attr('lat');
					$positionAdd.html($this.children('strong').html());
					bdMap.map.clearOverlays();
					var nowPoint = new BMap.Point($this.attr('lng'), $this.attr('lat'));
					bdMap.map.centerAndZoom(new BMap.Point(nowPoint), 14);		// 创建中心点为当前位置
					bdMap.map.addOverlay(new BMap.Marker(nowPoint));		// 添加客户位置
					bdMap.map.setCenter(nowPoint);
					setTimeout(function () {
						layer.closeAll();
					}, 500);
				}
			});


			// 点击完成按钮
			$('html body .header-title .btn em').on('tap', function () {
				inviteObj.site = $positionName.html();
				inviteObj.siteAdd = $positionAdd.html();
				inviteObj.sitePoint = {};
				inviteObj.sitePoint.lng = $positionName.attr('lng');
				inviteObj.sitePoint.lat = $positionName.attr('lat');
				inviteObj.city = city;
				// if (marker) {
				// 	inviteObj.site = marker.title;
				// 	inviteObj.siteAdd = marker.address;
				// 	inviteObj.sitePoint = {};
				// 	inviteObj.sitePoint.lng = marker.point.lng;
				// 	inviteObj.sitePoint.lat = marker.point.lat;
				// } else {
				// 	inviteObj.site = gpsDetail.result.poiRegions[0].name;
				// 	inviteObj.siteAdd = gpsDetail.result.formatted_address;
				// 	inviteObj.sitePoint = {};
				// 	inviteObj.sitePoint.lng = gpsDetail.result.location.lng;
				// 	inviteObj.sitePoint.lat = gpsDetail.result.location.lat;
				// }
				core.ls('inviteObj', 'o', inviteObj);
				core.back();
			});

			var bdMap = core.bdMap({
				selector: 'map',
				device: 'mb',
				map: true,
				gpsDetail: function (data) {		// 根据经纬度获取地址信息
					console.log(data)
					gpsDetail = data;
					city = data.result.addressComponent.city;
					$('html body .header-title h1').html(data.result.addressComponent.city);
					if (inviteObj.site) {
						$positionName.html(inviteObj.site).attr({
							lng: inviteObj.sitePoint.lng,
							lat: inviteObj.sitePoint.lat
						});
						$positionAdd.html(inviteObj.siteAdd);
						site = inviteObj.site;
						add = inviteObj.siteAdd;
					} else {
						if ((data.result.location.lng != 0) && (data.result.location.lat != 0)) {
							$positionName.html(data.result.poiRegions[0] ? data.result.poiRegions[0].name : '').attr({
								lng: data.result.location.lng,
								lat: data.result.location.lat
							});
							$positionAdd.html(data.result.formatted_address);
							site = (data.result.poiRegions[0] ? data.result.poiRegions[0].name : '');
							add = data.result.formatted_address;
						}
					}
				},
				setMap: function (map, x, y) {
					if ((x == 0) || (y == 0)) {
						bdMap.netLocation();
					}
					if ((x != 0) && (y != 0)) {

						if (inviteObj.sitePoint) {
							x = inviteObj.sitePoint.lng;
							y = inviteObj.sitePoint.lat;

							createPoint(x, y)
						} else {
							bdMap.gpsDetail(x, y, function (data) {
								createPoint(data.result.location.lng, data.result.location.lat)
							});
						}

						function createPoint(x, y) {
							// 添加返回按钮
							$('#map').append('<div id="goBack" style="height: 32px; position: absolute; z-index: 1200; text-size-adjust: none; bottom: 30px; right: auto; top: auto; left: 10px;"><div style="height: 32px; margin: 0px; box-sizing: border-box; border: 1px solid #d9d7d5; border-radius: 3px; -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2); overflow: hidden;"><div style="float: left; width: 32px; height: 32px; background-image: url(http://api0.map.bdimg.com/images/geolocation-control/mobile/gradient-bg-1x64.png); background-size: 1px 32px; background-repeat: repeat-x;"><div style="width: 32px; height: 32px; cursor: pointer; background-image: url(http://api0.map.bdimg.com/images/geolocation-control/mobile/default-40x40.png); background-size: 20px 20px; background-repeat: no-repeat; background-position: center center;"></div></div></div></div>');
							$('#goBack').on('tap', function () {
								map.clearOverlays();
								var nowPoint = new BMap.Point(lng, lat);
								bdMap.map.setZoom(14);
								bdMap.map.setCenter(new BMap.Point(lng, lat));
								map.centerAndZoom(new BMap.Point(nowPoint), 14);		// 创建中心点为当前位置
								map.addOverlay(new BMap.Marker(nowPoint));		// 添加客户位置
								map.setCenter(nowPoint);
								$positionName.html(site).attr({
									lng: lng,
									lat: lat
								});
								$positionAdd.html(add);
							});
							
							// // 添加定位控件
							// var geolocationControl = new BMap.GeolocationControl();
							// geolocationControl.addEventListener("locationSuccess", function(e){
							// 	// 定位成功事件
							// 	console.log(e)
							// 	var map = bdMap.map;
							// 	map.clearOverlays();
							// 	console.log(e.point.lng, e.point.lat)
							// 	// var point = new BMap.Point(lng, lat);		// 使用店铺的百度地图经纬度创建地图定位点
							// 	// map.addOverlay(new BMap.Marker(point));		// 添加当前位置
							// 	var nowPoint = new BMap.Point(e.point.lng, e.point.lat);
							// 	var nowPoint = new BMap.Point(0, 0);
							// 	map.centerAndZoom(new BMap.Point(nowPoint), 14);		// 创建中心点为当前位置
							// 	map.addOverlay(new BMap.Marker(nowPoint));		// 添加客户位置
							// 	map.setCenter(nowPoint);
							// 	console.log(e.point.lng, e.point.lat)
							// 	$.ajax({
							// 		// url: 'http://api.map.baidu.com/geocoder/v2/?location=' + x + ',' + y + '&ak=' + _this.obj.ak + '&coordtype=wgs84ll&pois=0&output=json',
							// 		// url: 'https://api.map.baidu.com/geocoder/v2/?location=' + e.point.lat + ',' + e.point.lng + '&ak=' + bdMap.obj.ak + '&coordtype=wgs84ll&pois=0&output=json',
							// 		url: 'https://api.map.baidu.com/geocoder/v2/?location=' + 0 + ',' + 0 + '&ak=' + bdMap.obj.ak + '&coordtype=wgs84ll&pois=0&output=json',
							// 		type: 'get',
							// 		dataType: 'jsonp',
							// 		jsonp: 'callback',
							// 		success: function (data) {
							// 			console.log(data)
							// 			$('html body .header-title h1').html(data.result.addressComponent.city);
							// 			$positionName.html(data.result.poiRegions[0] ? data.result.poiRegions[0].name : '').attr({
							// 				lng: data.result.location.lng,
							// 				lat: data.result.location.lat
							// 			});
							// 			$positionAdd.html(data.result.formatted_address);
							// 		}
							// 	});
							// 	// map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL})); 
							// });
							// geolocationControl.addEventListener("locationError",function(e){
							// 	// 定位失败事件
							// 	// alert(e.message);
							// });
							// map.addControl(geolocationControl);
							lng = x;
							lat = y;

							// var point = new BMap.Point(lng, lat);		// 使用店铺的百度地图经纬度创建地图定位点
							// map.addOverlay(new BMap.Marker(point));		// 添加当前位置
							var nowPoint = new BMap.Point(x, y);
							map.centerAndZoom(new BMap.Point(nowPoint), 14);		// 创建中心点为当前位置
							map.addOverlay(new BMap.Marker(nowPoint));		// 添加客户位置

							// map.addControl(new BMap.MapTypeControl());	 //添加地图类型控件

							map.enableScrollWheelZoom(true);		 //开启鼠标滚轮缩放
							map.setCenter(nowPoint);
							map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL})); 

							local = new BMap.LocalSearch(nowPoint, {
								// renderOptions:{
								// 	map: map,
								// },
								// onMarkersSet: function (markers) {
								// 	$('.BMap_Marker').on('touchend', function () {
								// 		marker = markers[$(this).index()];
								// 		$positionName.html(marker.title);
								// 		$positionAdd.html(marker.address);
								// 	});
								// },
								onSearchComplete: function (result) {
									console.log(result)
									// result && core.layerHint(result.keyword);
									searchResult = '';
									if (result) {
										for (var i = 0; i < lowercaseLetters.length; i++) {
											if (result[lowercaseLetters[i] + 'r']) {
												console.log(result[lowercaseLetters[i] + 'r'])
												if ($('.layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .input input').val() != '') {
													for (var j = 0; j < result[lowercaseLetters[i] + 'r'].length; j++) {
														searchResult += '<div lng="' + result[lowercaseLetters[i] + 'r'][j].point.lng + '" lat="' + result[lowercaseLetters[i] + 'r'][j].point.lat + '"><span>' + result[lowercaseLetters[i] + 'r'][j].title + '</span><strong>' + result[lowercaseLetters[i] + 'r'][j].address + '</strong></div>';
													}
												}
												break;
											}
										}
										$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con').html(searchResult);
									} else {
										$('body .layui-m-layer .layui-m-layermain .layui-m-layersection .map-search .layui-m-layercont article .con').html('');
									}
								}
							});
						}
					}
				}
			}, useBaidu);
		}
	});
}
